package com.huhao.concurrency.example.lock;

import com.huhao.concurrency.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 代码模拟并发测试
 * ReentrantReadWriteLock包演示
 */
@Slf4j
@ThreadSafe
public class ReentrantReadWriteLockExample {
    private final Map<String, Data> map = new TreeMap<>();
    private final ReentrantReadWriteLock Lock = new ReentrantReadWriteLock();
    private final Lock readLock = Lock.readLock();
    private final Lock writeLock = Lock.writeLock();

    public Data get(String key) {
        readLock.lock();
        try {
            return map.get(key);
        } finally {
            readLock.unlock();
        }
    }

    public Set<String> getAllKeys() {
        readLock.lock();
        try {
            return map.keySet();
        } finally {
            readLock.unlock();
        }
    }

    public Data put(String key, Data value) {
        //只能在所有读操作做完了，才能写（读很多，写少，可能造成写饥饿
        writeLock.lock();
        try {
            return map.put(key, value);
        } finally {
            writeLock.unlock();
        }
    }


    class Data {

    }
}
